import { mapMutations, mapActions, mapState } from "vuex";
import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
import dayjs from "dayjs";

const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.upperFirst(
      _.camelCase(
        name
          .split("/")
          .pop()
          .replace(/\.\w+$/, "")
      )
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      completeLoad: false,//验证所有元素是否全部加载完成
      me:this,
      watchs:[],
      models: {
        //模型

        accountPeriod: {
          ...typeClassName["accountPeriod"],
        },
        reductionRouting: {
          ...typeClassName["reductionRouting"],
        },
        masterPlan: {
          ...typeClassName["masterPlan"],
        },
      },
      onlyRead: false,
      productOptions: [],
      dataSet: {
        //数据集
        tableData: [],
        formData: {},
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map((item) => {
      this.$watch(item.target, item.fn, { deep: item.deep });
    });
    this.$nextTick(() => {
      this.unwatch = this.$watch("vms", (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      if (process.env.NODE_ENV === "development") {
        this.init();
        console.log({
          me: this,
          vms: this.vms,
          completeLoad: this.completeLoad,
        });
      }
    });
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    // 初始化
    init() {
      this.getProduct();
      let newFilter = {
        className: this.models.masterPlan.className,
        type: this.models.masterPlan.type,
      };
      this._$query(this.models.masterPlan.clzs, newFilter, "", "", false);
    },
    /**
     *
     * @param {分页} pageNavigation
     * @param {筛选条件} filter
     * 页面加载方法
     */
    loadPage(pageNavigation, filter) {
      this.vms.mainTable.loading = true;
      let data = {
        pageNumber: this.vms.mainTable.pageNavigation.pageNumber,
        pageSize: this.vms.mainTable.pageNavigation.pageSize,
        className: this.models.masterPlan.className,
        type: this.models.masterPlan.type,
        needRootFlag: false,
        condition: "parentId='root'",
        model: this.models.masterPlan.modelType,
        hierValueCondition: this._$setFilteStr(filter),
        orderBy: "updateTime",
      };
      this.$api.production.planQueryByPage(data).then((res) => {
        this.vms.mainTable.loading = false;
        console.log(res);
        this.dataSet.tableData = res.records.map((item) => {
          return {
            ...item,
            ...item.values,
          };
        });
        this.vms.mainTable.pageNavigation.total = res.total;
      });
    },

    /**
     * 新增-弹窗显示
     */
    handleCreate() {
      this._modalShow("createModal");
      this.dataSet.formData = this.$modelObject.getTpl(
        this.models.masterPlan.modelType
      ); // 这是一个整理接口数据JSON格式的方法
    },
    /**
     * 查看-弹窗显示
     * @param {*} row
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.formData = row;
    },
    /**
     * 编辑-弹窗显示
     * @param {*} row
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.formData = row;
    },
    /**
     * 删除单行
     * @param {行数据} row
     * @param {索引} index
     */
    handleDelete(row, index) {
      this._$deleteConfirm(() => {
        this.$api.production.deletePlan(row).then((flag) => {
          this.vms.mainTable.pageNavigation.pageNumber = 1;
          this.loadPage(this.vms.mainTable.pageNavigation, {});
        });
      });
    },
    /**
     * 执行方法
     * @param {行数据} row 
     * @param {索引} index 
     * @returns 
     */
    tableExecution(row, index) {
      if (row.status !== "创建") {
        this.$Message.error("已经执行过了，不能重复执行");
        return;
      }
      this.$api.production.toDoExecutePlan(row).then((res) => {
        // this.dataSet.leftTableData.splice(index, 1, ele);
        this.vms.mianTable.pageNavigation.pageNumber = 1;
        this.leftLoadPage(this.vms.leftTable.pageNavigation, {}, "");
        console.log(this.dataSet.leftTableData);
      });
    },
    // 创建提交
    createModalOk() {
      // this.vms.createView.validate((valid) => {
      this.vms.createModal.loading = true;
      this.vms.createView.validate((valid) => {
        if (valid) {
          let newData = {
            values: this.dataSet.formData.values,
            containerModel: this.models.masterPlan.modelType,
            containerId: this.models.masterPlan.clzs.valueRecords[0].id,
            parentId: "root",
          };

          this.$api.production.initRouting(newData).then((res) => {
            this.loadPage(this.vms.mainTable.pageNavigation, {});
            this._modalClose("createModal");
            this._resetForm("createView");
          });
        }
        this.vms.createModal.loading = false;
      });
    },

    editModalOk(btn) {
      this.vms.editView.validate((valid) => {
        if (valid) {
          this.models.reductionRouting.clz.setRecord(this.dataSet.formData);
          this.models.reductionRouting.clz.updateById().then((flag) => {
            if (flag) {
              this.vms.editView.loading = false;
              this.vms.editModal.show = false;
              this._modalClose("editModal");
              btn.loading = false;
              this._resetForm("editView");
              this.vms.mainTable.pageNavigation.pageNumber = 1;
              this.loadPage(
                this.vms.mainTable.pageNavigation,
                {},
                "",
                "",
                false
              );
            } else {
              btn.loading = false;
            }
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
